Java使用cmd调用nodejs脚本 | 您所在的位置:网站首页 › nodejs 调用cmd › Java使用cmd调用nodejs脚本 |
简述
本博客不是讲使用Java提供的js脚本引擎编写js脚本,而是业务需要,本地模拟http请求动态调用nodejs脚本(本地测试openfaas函数编程,模拟http请求调用nodejs函数) 虽然Java有提供执行js脚本的执行引擎,但是在使用时,并不是那么好用,所以测试时使用cmd调用nodejs。 代码需求:调用nodejs并传参数 Java: String json = "{\"name\":\"yz\"}"; json = JSON.toJSONString(json); try { String filename = "C:\\Users\\80022319\\Desktop\\" + "test" + ".txt"; FileOutputStream outputStream = new FileOutputStream(filename); byte[] bytes = json.getBytes(Charset.forName("UTF-8")); outputStream.write(bytes); outputStream.flush(); outputStream.close(); Process exec = Runtime.getRuntime().exec("cmd /c start C:\\Users\\80022319\\Desktop\\node\\exe.bat " + filename); int i = exec.waitFor(); System.out.println(i); exec.destroy(); } catch (Exception e) { e.printStackTrace(); }bat脚本:创建exe.bat脚本 C: cd C:\Users\80022319\Desktop\node\ set filename=%1% for /f %%i in ('type %filename%') do ( set commitid=%%i) node index.js %commitid%NodeJs let args = process.argv.splice(2); let filename = args[0]; let fs = require('fs'); let val = fs.readFileSync(filename); val = val.toString(); 注意如果脚本中不指定目录和文件夹,脚本中执行其他脚本时,默认寻找工程所在目录下的index.js文件 我的工程在D:\workspace\git\open\clife-iot, 我的脚本在C:\\Users\\80022319\\Desktop\\node\\exe.bat 脚本中又指定了目录并进入指定文件夹 C: cd C:\Users\80022319\Desktop\node\java中执行脚本的命令用cmd /c start,让os打开一个cmd命令窗口执行bat脚本,这样可以更好的看到窗口中输出的内容 cmd执行脚本并传参,参数有字符限制,如果是参数字符太多,请使用读文件的方式。 |
CopyRight 2018-2019 实验室设备网 版权所有 |